package com.cinema.api.service.Impl;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cinema.api.model.entity.Upload;
import com.cinema.api.mapper.UploadMapper;
import com.cinema.api.model.exception.BizException;
import com.cinema.api.service.UploadService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cinema.api.utils.BaseUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xhh
 * @since 2021-12-31
 */
@Service
public class UploadServiceImpl extends ServiceImpl<UploadMapper, Upload> implements UploadService {

    @Resource
    private UploadMapper uploadMapper;


    /**
     *  通过md5值检验文件，并保存到`upload`数据库表中
     *  返回ID字段
     */
    @Override
    public String checkAndSaveUpload(MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();
            // 获取文件大小
            byte[] data = new byte[(int) file.getSize()];
            int i = inputStream.read(data);
            System.out.println("上传文件的大小：" + i);
            // 对上传文件进行md5加密
            String md5 = DigestUtils.md5DigestAsHex(data);
            // 判断 上传文件的MD5值 是否与 数据库中已存在文件的md5值 相同
            QueryWrapper<Upload> wrapper = new QueryWrapper<>();
            wrapper.eq("md5", md5).eq("is_delete", 0);
            Upload upload = uploadMapper.selectOne(wrapper);
            // 如果存在相同的值则直接返回已存在的文件ID(防止重复插入，占用内存)
            if (BaseUtil.isNotEmpty(upload)) {
                return upload.getId();
            }
            // 不存在则插入数据库中，并返回ID值
            String id = UUID.randomUUID().toString();
            uploadMapper.insert(new Upload(id, data, md5, new Date(), 0));
            return id;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
